//
//  MCCameraEventProcess.m
//  CreditGroup
//
//  Created by ltl on 15/9/11.
//  Copyright (c) 2015年 JPlay. All rights reserved.
//

#import "MCCameraEventProcess.h"
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
#import <AssetsLibrary/AssetsLibrary.h>

#import "MCCameraImageRotationHandle.h"
#import "MCCameraImageClipHandle.h"
#import "MCCameraCompressHandle.h"
#import "YSHYClipViewController.h"

@interface MCCameraEventProcess ()<UINavigationControllerDelegate,
                                  UIImagePickerControllerDelegate,
                                            UIActionSheetDelegate,ClipViewControllerDelegate>

{
    UIViewController *rootViewController;
}

@property (strong, nonatomic) UIImage *returnImage;

@end

@implementation MCCameraEventProcess
-(instancetype)init
{
    self = [super init];
    if (self)
    {
        NSLog(@"MCCameraEventProcess init is success");
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        rootViewController = window.rootViewController;
        
    }
    return self;
}
- (void)setIsClip:(EMCCameraIsClip)isClip{
    _isClip = isClip;
}

- (void)setRotation:(EMCImageRotationType)rotation{
    _rotation = rotation;
}

- (void)setSize:(CGSize)size{
    _size = size;
}

- (void)setFormat:(EMCImageFormat)format{
    _format = format;
}

- (void)setQuality:(CGFloat)quality{
    _quality = quality;
}

- (void)transmitClickEventsWithActionSheetType:(EActionSheetEventType)actionSheetType
                                   isHaveFrame:(EMCCameraIsHaveFrame)isHaveFrame
{
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    [picker.navigationBar setTintColor:[UIColor whiteColor]];
    picker.delegate = self;
    picker.allowsEditing = isHaveFrame;

    EActionSheetEventType type = actionSheetType;
    switch (type)
    {
        case kActionSheetEventTypePhoto:
            [self openWithPhoto:picker];
            break;
        case kActionSheetEventTypeCamera:
            [self openWithCamera:picker];
            break;
        case kActionSheetEventTypeCancel:
            return;
            break;
            
        default:
            break;
    }
}

- (void)openWithCamera:(UIImagePickerController *)picker
{
    NSLog(@"打开相机");
    //判断相机是否可用
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        
        NSString *mediaType = AVMediaTypeVideo;
        
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
        
        if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied)
        {
            
            UIAlertController *alertCV = [UIAlertController alertControllerWithTitle:@"提示"
                                                                             message:@"请到“设置--隐私--相机”获取相机权限"
                                                                      preferredStyle:UIAlertControllerStyleAlert];
            
            
            [rootViewController.navigationController pushViewController:alertCV animated:YES];
            
            return;
            
        }
        else
        {
            CGFloat version = [[[UIDevice currentDevice] systemVersion] floatValue];
            rootViewController.modalPresentationStyle = (version < 8 ? UIModalPresentationCurrentContext : UIModalPresentationOverCurrentContext);
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [rootViewController presentViewController:picker animated:YES completion:^
            {
                NSLog(@"present 弹出相机控制器");
            }];
        }
    }else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"相机不可用"
                                                       delegate:nil
                                              cancelButtonTitle:@"知道了"
                                              otherButtonTitles:nil];
        [alert show];
    }
    
}
- (void)openWithPhoto:(UIImagePickerController *)picker
{
    NSLog(@"打开相册");
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        
        ALAuthorizationStatus authStatusOld = [ALAssetsLibrary authorizationStatus];
        PHAuthorizationStatus authStatusNew = [PHPhotoLibrary  authorizationStatus];
        CGFloat version = [[[UIDevice currentDevice] systemVersion] floatValue];;
        
        if((version < 8.0 ? ( authStatusOld == ALAuthorizationStatusRestricted || authStatusOld == ALAuthorizationStatusDenied) : (authStatusNew == PHAuthorizationStatusRestricted || authStatusNew == PHAuthorizationStatusDenied)))
        {
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"请为“信贷圈”授权访问您的相册"
                                                           delegate:nil
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:nil];
            [alert show];
            
            return;
            
        }
        else
        {
            
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//设置PickerC type（相册、相机）
            [rootViewController presentViewController:picker animated:YES completion:^
            {
                NSLog(@"present 弹出相册控制器");

            }];
        }
    }

}

#pragma mark - UIImagePickerControllerDelegate method
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{

    if (_isClip) {
        // 裁剪
        YSHYClipViewController * clipView = [[YSHYClipViewController alloc]initWithImage:image];
        clipView.delegate = self;
        clipView.clipType = SQUARECLIP; //支持圆形:CIRCULARCLIP 方形裁剪:SQUARECLIP   默认:圆形裁剪
        //    clipView.scaleRation = 5;// 图片缩放的最大倍数 默认为10
        [picker pushViewController:clipView animated:YES];

    }else{
        // 判断是否需要处理图片
        if (_type == kMCImageTypeNomal || _type == kMCImageTypeImage) {
            UIImage *dealedImg = [self toDealWithPicturesReturnImage:image];
            if (self.returnImageBlock)
            {
                self.returnImageBlock(dealedImg);
            }
        }
        if (_type == kMCImageTypeData) {
            NSData *dealedImgData = [self toDealWithPicturesReturnData:image];
            if (self.returnImageDataBlock)
            {
                self.returnImageDataBlock(dealedImgData);
            }
        }
        [picker dismissViewControllerAnimated:YES completion:^
         {
             [rootViewController dismissViewControllerAnimated:NO completion:^
              {
                  NSLog(@"从相机类退出");
              }];
         }];
    }
}

#pragma mark - ClipViewControllerDelegate
-(void)ClipViewController:(YSHYClipViewController *)clipViewController FinishClipImage:(UIImage *)editImage
{
    [clipViewController dismissViewControllerAnimated:YES completion:^{
        // 判断是否需要处理图片
        
        if (_type == kMCImageTypeNomal || _type == kMCImageTypeImage) {
            UIImage *dealedImg = [self toDealWithPicturesReturnImage:editImage];
            if (self.returnImageBlock)
            {
                self.returnImageBlock(dealedImg);
            }
        }
        if (_type == kMCImageTypeData) {
            NSData *dealedImgData = [self toDealWithPicturesReturnData:editImage];
            if (self.returnImageDataBlock)
            {
                self.returnImageDataBlock(dealedImgData);
            }
        }
    }];
}

- (UIImage *)toDealWithPicturesReturnImage:(UIImage *)image{
    UIImage *contextImg = nil;
    if (image) {
        // 旋转
        contextImg = [MCCameraEventProcess imageWithRotationType:_rotation image:image];
        // 压缩
        contextImg = [MCCameraEventProcess imageCompressWith:_size image:contextImg];
    }
    // 格式
    
    return contextImg;
}

- (NSData *)toDealWithPicturesReturnData:(UIImage *)image{
    UIImage *contextImg = nil;
    NSData *contextImgData = nil;
    // 旋转
    contextImg = [MCCameraEventProcess imageWithRotationType:_rotation image:image];
    // 压缩
    contextImg = [MCCameraEventProcess imageCompressWith:_size image:contextImg];
    
    // 转化格式
    if (_format == kMCImageFormatPNG || _format == kMCImageFormatDefault) {
        if (image) {
            contextImgData = [MCCameraCompressHandle imageDataWithJEPG:contextImg quality:_quality];
        }
    }
    if (_format == kMCImageFormatJPEG) {
        if (image) {
            contextImgData = [MCCameraCompressHandle imageDataWithPNG:contextImg];
        }
    }
    
    return contextImgData;
}

+ (UIImage *)imageWithRotationType:(EMCImageRotationType)rotationType image:(UIImage *)image
{
    return [MCCameraImageRotationHandle processImagesWithType:rotationType image:image];
}

+ (UIImage *)imageClipWith:(CGRect)rect image:(UIImage *)image
{
    return [MCCameraImageClipHandle imageClipWith:rect image:image];
}

+ (UIImage *)imageCompressWith:(CGSize)size image:(UIImage *)image
{
    return [MCCameraCompressHandle imageCompressWith:size image:image];
}

+ (NSData *)imageDataWithJEPG:(UIImage *)image quality:(CGFloat)value
{
    return [MCCameraCompressHandle imageDataWithJEPG:image quality:value];
}

- (void)dealloc{
    NSLog(@"MCCameraEventProcess = nil");
}
@end
